package com.motu.monstercity.server.game.web;


import com.motu.monstercity.server.game.logic.MailManager;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.motu.vertx.module.utility.webtool.CommonTableManager;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GamemailHandler extends BaseWebHandler{
	private static Logger logger = LoggerFactory.getLogger(GamemailHandler.class);
	/*
	 * 后台前端请求的发送邮件接口
	 */
	public static void send(RoutingContext routingContext, JsonObject json, String adminName, WebClient client){
		int condition = json.getInteger("condition");
		String sql = "";
		JsonArray params = new JsonArray();
		String p = json.getString("param");
		String str1 = "select a.id from user_info a, user_ext_info b where a.id = b.id ";
		if(condition == 1){  //注册时间
			sql = str1 +" and b.register_time >= ? and b.register_time <= ? ";
			params.add(json.getInteger("starttime"));
			params.add(json.getInteger("endtime"));
		}else if(condition == 2){  //最后登录时间
			sql = str1+" and a.login_time >= ? and a.login_time <= ?";
			params.add(json.getInteger("starttime"));
			params.add(json.getInteger("endtime"));
		}else if(condition == 3){  //充值满额送
			sql = str1+" and b.iap_buy >= ?";
			params.add(Integer.parseInt(p));
		}else if(condition == 4){   //连续登录x天
			sql = str1+" and b.login_day_count >= ?";
			params.add(Integer.parseInt(p));
		}else if(condition == 5){  //等级>=
			sql = str1+" and a.level >= ?";
			params.add(Integer.parseInt(p));
		}else if(condition == 6){   //vip=
			sql = str1+" and a.vip = ?";
			params.add(Integer.parseInt(p));
		}else if(condition == 7){  //vip >=
			sql = str1+" and a.vip >= ?";
			params.add(Integer.parseInt(p));
		}else if(condition == 8){  //指定用户id
			sql = "select a.id from user_info a, user_ext_info b where a.id=b.id and a.id in (" + p + ")";
		}else if(condition == 9) {  //指定角色名
			sql = str1 + " and a.user_name = ?";
			params.add(p);
		}

//		}else if(condition == 10){   //帮派等级>=
//			sql = "SELECT a.id, b.language FROM familymember a, userextinfo b where a.id=b.id and a.familyid in(select id from family where level >= ?) ";
//			params.add(Long.parseLong(p));
//			if (json.containsKey("slist")) {
//				sql += " and b.sid in (" + json.getString("slist") + ")";
//			}
//		}else if(condition == 11){  //帮派id=
//			sql = "SELECT a.id, b.language FROM familymember a, userextinfo b where a.id=b.id and a.familyid = ?;";
//			params.add(Long.parseLong(p));
//		}

		JsonObject titleDesData = setDesData(json.getString("title"));
		JsonObject contentDesData = setDesData(json.getString("content"));
		String titleWordHashcode = Tool.actWordHashcode(2, titleDesData);
		String contentWordHashcode = Tool.actWordHashcode(2, contentDesData);
		if (titleWordHashcode.equals(contentWordHashcode)) {
			sendHttpResponseError(routingContext.response(), "邮件标题和内容不能同时设置一样的!!!");
			return;
		}
		logger.info(Tool.getSqlString(sql, params));  //日志记录查询userid的sql语句

		byte mailType = json.getInteger("mailtype") == 1 ? (byte) 1 : (byte) 0;// 邮件类型0-普通邮件,1-重要邮件
		int logType = json.getInteger("logtype");
		String item = json.getString("item");// 奖励
		Future<Long> futureTitle = CommonTableManager.takeActWordId(MysqlClient.getServerPool(), 2, titleDesData, mailType);//2:代表后台发邮件
		Future<Long> futureContent = CommonTableManager.takeActWordId(MysqlClient.getServerPool(), 2, contentDesData, mailType);//2:代表后台发邮件
		Future<JsonArray> futureUser = MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params);// 查询符合条件的userid列表
		HttpServerResponse response = routingContext.response();
		CompositeFuture.all(futureTitle, futureContent).onComplete(actWordHandler->{
			if (actWordHandler.succeeded()) {
				GamehttpgmHandler.publishReloadActWord();// 广播重载act_word表

				long titleId = futureTitle.result();
				long contentId = futureContent.result();
				JsonArray userIdList = futureUser.result();
				JsonObject result = new JsonObject().put("num", userIdList.size());
				if (userIdList.size() > 0) {
					sendMail(userIdList, titleId, contentId, logType, mailType, item);
				}
				sendHttpResponse(response, result);
			} else {
				sendHttpResponseError(routingContext.response(), actWordHandler.cause().getMessage());
			}
		});
	}
	
	// 发送邮件
	private static void sendMail(JsonArray list, long titleId, long contentId, int logType, byte mailType, String item){
		for (int i=0; i<list.size(); i++) {
			JsonObject jsonObject = list.getJsonObject(i);
			long userId = jsonObject.getLong("id");
			MailManager.sendWebMail(userId, titleId, contentId, item, logType, mailType);
		}
	}

	private static JsonObject setDesData (String str) {
		JsonObject desDate = new JsonObject();
		try {
			JsonArray array = new JsonArray(str);
			for (int i=0; i<array.size(); i++) {
				JsonObject obj = array.getJsonObject(i);
				int type = obj.getInteger("type");
				String val = obj.getString("word");
				desDate.put("des_"+type,val);
			}
			return desDate;
		} catch(Exception e) {
			logger.error("GamemailHandler sendMail setDesData  error : " + Tool.getException(e));
			return desDate;
		}
	}
}
